<!-- 项目存档申请 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请时间" prop="createTime" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="proposer" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请人部门" prop="proposerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.proposerDeptId"
            :departName="model.proposerDeptIdText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptIdText"
          ></h-select-depart-input>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">项目信息</view>
        <u-form-item label="项目名称" prop="projectId" required>
          <h-select-project-input-popup
            :proDisabled="true"
            :projectStatus="'2'"
            ref="projectSelect"
            v-model="model.projectId"
            style="width: 100%"
            placeholder="请选择项目名称"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :api="api.queryOmcProjectList"
          ></h-select-project-input-popup>
          <!-- @change="onChangeProjectName" -->
        </u-form-item>
        <u-form-item label="项目编号" prop="projectNo">
          <u--input disabled placeholder="请输入项目编号" v-model="model.projectNo"></u--input>
        </u-form-item>
        <u-form-item label="签订单位" prop="signUnit">
          <h-select-company-input-popup
            disabled
            style="width: 100%"
            v-model="model.signUnit"
            commercialType="1"
            placeholder="请选择签订单位"
            border="surround"
          ></h-select-company-input-popup>
        </u-form-item>
        <u-form-item label="经营团队" prop="managementTeam">
          <h-select-team-input
            disabled
            style="width: 100%"
            v-model="model.managementTeam"
            objectField="model.managementTeam"
            placeholder="请选择经营团队"
            border="surround"
            :tdlx="1"
          />
        </u-form-item>
        <u-form-item label="项目承接人" prop="undertaker">
          <h-select-person-input-popup
            disabled
            v-model="model.undertaker"
            style="width: 100%"
            placeholder="请选择项目承接人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="项目地址" prop="area" :borderBottom="false">
          <h-select-address-input
            disabled
            style="width: 100%"
            v-model="model.area"
            placeholder="请选择项目地址"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-address-input>
        </u-form-item>
        <u-form-item label="业务名称" prop="businessName" required>
					<h-select-task-file-input-popup
					  :projectId="model.projectId"
					  v-model="model.businessName"
					  class="w-100"
					  :disabled="!model.projectId"
					  :placeholder="model.projectId ? '请选择任务编号' : '请先选择项目'"
					  searchPlaceholder="请输入任务编号"
					  border="surround"
					  label="billNo"
					  suffixIcon="arrow-down-fill"
					  :suffixIconStyle="{ color: '#B2B2B2' }"
						:customParams="{
						  distributionType: 'finish,producting',
						}"
					  @realChange="onTaskIdInput"
					  @select="model.taskDescription = $event.taskDescription"
					></h-select-task-file-input-popup>
        </u-form-item>
        <u-form-item label="任务编号" prop="taskNo" :borderBottom="false">
          <u--input v-model="model.taskNo" disabled placeholder="请输入任务编号" border="surround"></u--input>
        </u-form-item>
        <u-form-item label="实施部门" prop="implementationDepartment" :borderBottom="false">
          <h-select-depart-input
            v-model="model.implementationDepartment"
            :departName="model.implementationDepartmentText"
            placeholder="请选择部门"
            disabled
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.implementationDepartmentText"
            @detail="onExecuteDepartInput"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="生产团队" prop="productionTeam" :borderBottom="false">
          <h-select-team-input
            style="width: 100%"
            disabled
            v-model="model.productionTeam"
            objectField="model.productionTeam"
            placeholder="请选择生产团队"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :tdlx="2"
          ></h-select-team-input>
        </u-form-item>
        <u-form-item label="项目负责人" prop="projectLeader" :borderBottom="false">
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.projectLeader"
            placeholder="请选择项目负责人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.projectLeader"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="行业类别" prop="industryCategory" :borderBottom="false">
          <h-dict-select
            style="width: 100%"
            disabled
            v-model="model.industryCategory"
            placeholder="请选择行业类别"
            dictName="industry_category"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-dict-select>
        </u-form-item>
        <u-form-item label="审批级别" prop="approvalLevel" :borderBottom="false">
          <h-dict-select
            style="width: 100%"
            disabled
            v-model="model.approvalLevel"
            placeholder="请选择审批级别"
            dictName="approval_level"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-dict-select>
        </u-form-item>

        <u-form-item label="审批机构" prop="approvalAuthority">
          <u--input placeholder="请输入审批机构" v-model="model.approvalAuthority"></u--input>
        </u-form-item>
        <u-form-item label="投资额（元）" prop="investmentAmount">
          <h-money-input placeholder="请输入投资额（元）" v-model="model.investmentAmount"></h-money-input>
        </u-form-item>
        <u-form-item label="规模" prop="scale">
          <u--input placeholder="请输入规模" v-model="model.scale"></u--input>
        </u-form-item>
        <u-form-item label="批复文号" prop="approvalDocumentNo">
          <u--input placeholder="请输入批复文号" v-model="model.approvalDocumentNo"></u--input>
        </u-form-item>
        <u-form-item label="批复日期" prop="approvalDate">
          <h-time-select
            v-model="model.approvalDate"
            placeholder="请选择批复日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">存档信息</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="handleAddMember">新增</u-button>
        </view>
        <u-collapse>
          <u-collapse-item :title="item.archiveName" v-for="(item, index) in formData" :key="index">
            <FormInfo :item="item" :index="index" @edit="handleEditForm" @remove="handleRemoveForm" @copy="handleCopyForm" />
          </u-collapse-item>
        </u-collapse>
        <u-popup mode="bottom" :show="showFormModal" :closeOnClickOverlay="false" @close="closeFormModal" @open="openFormModal">
          <projectArchiveForm ref="dataForm" :index="index" @submit="handleFormSubmit" @close="showFormModal = false" />
        </u-popup>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.attachments" :isIcon="false"></h-upload-file>
          <file-list v-if="model.attachments" v-model="model.attachments" :isDelete="true"></file-list>
        </view>
      </view>
      <view class="space-x-1 px-1 btn_position">
        <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
      </view>
      <view style="height: 100rpx"></view>
      <u-toast ref="uToast"></u-toast>
      <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
    </u-form>
  </view>
</template>
  
  <script>
import { mapState } from 'vuex'
import moment from 'moment'
// import { erpProgressTemplateDtList } from '@/api/index'
import { queryOmcProjectList } from '@/api/index.js'
import { gainBillNo, add, edit, info, allListNoPage } from '@/api/project/erpProjectArchiveForm'
// import http from '@/utils/request/index'
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import fileList from '@/pages/synergy/components/fileList.vue'
import projectArchiveForm from './components/projectArchiveForm.vue'
import FormInfo from './components/projectArchiveFormInfo.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗

export default {
  name: 'ErpProjectArchiveForm',
  components: {
    fileList,
    projectArchiveForm,
    FormInfo,
    ProcessNodeConfiguration,
  },
  data() {
    return {
      isSubmit: false, // 控制按钮是否可以点击
      index: null,
      showFormModal: false,
      loading: false,
      id: '',
      basicForm: {},
      dictOptions: {},
      formData: [],
      api: {
        queryOmcProjectList,
      },
      model: {
        bpmBizTitle: '',
        billNo: '',
        createTime: '',
        proposer: '',
        proposerDeptId: '',
        projectId: '',
        projectNo: '',
        signUnit: '',
        undertaker: '',
        projectAddress: '',
        businessName: '',
        taskNo: '',
        implementationDepartment: '',
        productionTeam: '',
        projectLeader: '',
        industryCategory: '',
        approvalLevel: '',
        approvalAuthority: '',
        investmentAmount: '',
        scale: '',
        approvalDocumentNo: '',
        approvalDate: '',
        archiveMajorCategory: '',
        archiveMinorCategory: '',
        archiveBelongingTeam: '',
        secrecyLevel: '',
        attachments: null,
      },
      rules: {
        billNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
        proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
        proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
        createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],

        projectId: [{ required: true, message: '请选择项目名称!', trigger: ['blur', 'change'] }],
        businessName: [{ required: true, message: '请选择业务名称!', trigger: ['blur', 'change'] }],
        archiveMajorCategory: [{ required: true, message: '请选择档案大类!', trigger: ['blur', 'change'] }],
        archiveMinorCategory: [{ required: true, message: '请选择档案小类!', trigger: ['blur', 'change'] }],
        archiveBelongingTeam: [{ required: true, message: '请选择档案所属团队!', trigger: ['blur', 'change'] }],
        secrecyLevel: [{ required: true, message: '请选择密级!', trigger: ['blur', 'change'] }],
      },
      projectIdBackups: null,
      //代码生成后需手动设置流程编码
      flowCode: 'onl_erp_project_archive',
      formUrl: '/erp/omc/projectarchive/modules/ErpProjectArchiveForm',
      formUrlMobile: '/pages/synergy/erpProjectArchiveForm',
      beanName: 'erpProjectArchiveServiceImpl',
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  onReady() {
    this.$refs.projectSelect.$on('change', (event) => {
      this.onChangeProjectName(event)
    })
  },
  onUnload() {
    this.$off('change')
  },
  created() {
    if (this.id) {
      this.initInfo()
      this.initDataList()
    } else {
      this.initForm()
      this.initBillNo()
    }
    this.initDictConfig()
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home',
            })
          }
        },
      })
    },
    //清除所有带出数据
    resetData() {
      //带出项目编号
      this.$set(this.model, 'projectNo', '')

      //带出项目真实名称
      this.$set(this.model, 'projectName', '')

      //带出签订单位
      this.$set(this.model, 'signUnit', '')

      //带出项目承接人
      this.$set(this.model, 'undertaker', '')

      //带出经营团队
      this.$set(this.model, 'managementTeam', '')

      //带出项目地址
      this.$set(this.model, 'areaCode', '')

      //带出项目地址
      this.$set(this.model, 'projectAddress', '')

      //清除业务分类
      this.$set(this.model, 'businessName', '')

      //带出任务编号
      this.$set(this.model, 'taskNo', '')

      //带出实施部门
      this.$set(this.model, 'implementationDepartment', '')

      //带出生产团队
      this.$set(this.model, 'productionTeam', '')

      //带出项目负责人
      this.$set(this.model, 'projectLeader', '')

      //带出行业类别
      this.$set(this.model, 'industryCategory', '')

      //带出审批级别
      this.$set(this.model, 'approvalLevel', '')
    },
    // 选择项目名称
    async onChangeProjectName(event) {
      let backItem = event
      if (!event) {
        this.projectIdBackups = null
        //带出项目编号
        this.$set(this.model, 'projectNo', '')

        //带出项目真实名称
        this.$set(this.model, 'projectName', '')

        //带出签订单位
        this.$set(this.model, 'signUnit', '')

        //带出项目承接人
        this.$set(this.model, 'undertaker', '')

        //带出经营团队
        this.$set(this.model, 'managementTeam', '')

        //带出项目地址
        this.$set(this.model, 'area', '')

        //带出项目地址
        this.$set(this.model, 'projectAddress', '')
        return false
      }

      if (!this.projectIdBackups) {
        this.projectIdBackups = this.model.projectId
        //带出项目编号
        this.$set(this.model, 'projectNo', event.finalNo)

        //带出项目真实名称
        this.$set(this.model, 'projectName', event.projectName)

        //带出签订单位
        this.$set(this.model, 'signUnit', event.signUnit)

        //带出项目承接人
        this.$set(this.model, 'undertaker', event.undertaker)

        //带出经营团队
				this.$set(this.model, 'managementTeam', event.oldTeamId ? event.oldTeamId : event.teamName)

        //带出项目地址
        this.$set(this.model, 'area', event.areaCode)

        //带出项目地址
        this.$set(this.model, 'projectAddress', event.projectAddress)
      }
      //切换项目清空子表弹窗提示
      if (this.projectIdBackups && this.projectIdBackups !== backItem.id) {
        const that = this

        uni.showModal({
          title: '确认切换项目',
          content: '切换项目会清空所有任务相关信息，您确定要切换吗？',
          success: (res) => {
            if (res.confirm) {
              //确认后进行改变
              that.projectIdBackups = that.model.projectId

              //清空所有带出数据
              that.resetData()

              //带出项目编号
              that.$set(that.model, 'projectNo', backItem.finalNo)

              //带出项目真实名称
              that.$set(that.model, 'projectName', backItem.projectName)

              //带出签订单位
              that.$set(that.model, 'signUnit', backItem.signUnit)

              //带出项目承接人
              that.$set(that.model, 'undertaker', backItem.undertaker)

              //带出经营团队
							that.$set(that.model, 'managementTeam', backItem.oldTeamId ? backItem.oldTeamId : backItem.teamName)
              //带出项目地址
              that.$set(that.model, 'area', backItem.areaCode)

              //带出项目地址
              that.$set(that.model, 'projectAddress', backItem.projectAddress)
            } else if (res.cancel) {
              that.model.projectId = that.projectIdBackups
            }
          },
        })
      }
    },

    // 选择任务编号
    onTaskIdInput(event) {
      if (!event) {
        //带出任务编号
        this.$set(this.model, 'taskNo', '')

        //带出实施部门
        this.$set(this.model, 'implementationDepartment', '')

        //带出生产团队
        this.$set(this.model, 'productionTeam', '')

        //带出项目负责人
        this.$set(this.model, 'projectLeader', '')

        //带出行业类别
        this.$set(this.model, 'industryCategory', '')

        //带出审批级别
        this.$set(this.model, 'approvalLevel', '')
        return false
      }
      //带出任务编号
      this.$set(this.model, 'taskNo', event.billNo)
      //带出实施部门
      this.$set(this.model, 'implementationDepartment', event.executeDepart)
      //带出生产团队
      this.$set(this.model, 'productionTeam', event.productTeam)
      //带出项目负责人
      this.$set(this.model, 'projectLeader', event.projectLeading)
      //带出行业类别
      this.$set(this.model, 'industryCategory', event.industryCategory)
      //带出审批级别
      this.$set(this.model, 'approvalLevel', event.approvalLevel)
    },

    // 选择实施部门
    onExecuteDepartInput(item) {},
    initDictConfig() {
      initDictOptions('erp_omc_project_task,category_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'businessName', res.result)
        }
      })
      initDictOptions('erp_omc_project,project_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'projectId', res.result)
        }
      })
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    // 新增物料
    handleAddMember() {
      this.index = null
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, data)
      } else {
        this.formData.push(data)
      }
      // this.initBuyerInfo()
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({})
      this.model.billNo = res.result
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      this.model = Object.assign({}, data)
      //如果有项目id说明是编辑页面，就把原始id给它
      if (this.model.projectId) {
        this.projectIdBackups = this.model.projectId
      }
    },
    async initDataList() {
      const response = await allListNoPage({ mainId: this.id })
      const data = response.success ? response.result : []
      this.formData = data
    },
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        if (!this.formData.length) {
          this.$u.toast('请添加存档信息！')
          return Promise.reject('请添加存档信息！')
        }
        return Promise.resolve()
      })
    },
    setBpmBizTitle() {
      var projectName = filterMultiDictText(this.dictOptions['projectId'], this.model.projectId + '')
      var businessName = filterMultiDictText(this.dictOptions['businessName'], this.model.businessName + '')
      this.$set(
        this.model,
        'bpmBizTitle',
        '项目存档申请单 - ' + (this.model.projectId?projectName +' - ' :'') + (this.model.businessName? businessName +' - ' :'') +this.userInfo?.employee?.name +' - ' +moment(this.model.createTime).format('YYYY-MM-DD'),
      )
    },
    // checkFormData() {
    //   if (!this.formData.length > 0) {
    //     this.$u.toast('请添加存档信息！')
    //     return
    //   }
    // },
    async onSubmit() {
      await this.validateForm()

      this.isSubmit = true

      this.setBpmBizTitle()
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
          details: this.formData,
        })
        // this.$u.toast(response.message)
        if (response.success) {
          var that = this
          this.isSubmit = true
          // 获取流程列表
          if (this.model.id) {
            this.getProcessList(this.model.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              this.getProcessList(response.result)
            }
          }
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              // that.isSubmit = false
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 获取流程列表
    getProcessList(id) {
      if (this.isSubmit) {
        this.$refs.processConfig.showPopup = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(id, this.processId, this.beanName)
      }
    },
    // async onDraft() {
    //   await this.validateForm()
    // },
    async onDraft() {
      // await this.validateForm()

      this.isSubmit = true

      this.setBpmBizTitle()
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
          details: this.formData,
        })
        if (response.success) {
          this.isSubmit = true
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              this.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home',
                })
              }
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
  }
}
</script>
  
  <style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
  